import React, { useEffect, useState } from 'react';
import './style/newPass.css';
import { NavBar, Button, Input, Toast, Form} from 'react-vant';
import { useNavigate,useLocation } from 'react-router-dom';
import type { loginType } from '../../types/login';
import { handleChangePassword,getUsers } from '../../utils/api'
const NewPassword: React.FC = () => {
    const location = useLocation();
    const email = location.state?.email ||  '无相应的信息';
    const [formValues, setFormValues] = useState<loginType>({ password: '',confirmPassword:'' });
    const [form] = Form.useForm();
    const [showPassword, setShowPassword] = useState({
        password: false,
        confirmPassword: false
    });

    const navigate = useNavigate();
    const [isLoading, setIsLoading] = useState(false); // 新增加载状态
    const [id,setId] = useState(null)
    const onFinish = async () => {
        if( !email ) return;
        try{
            setIsLoading(true);
            Toast.loading({
                message:"请稍等...",
                forbidClick:true,
                duration:3000,
            })
          
            console.log(123);
            
            const params={
                _id:id,
                email:email,
                password:formValues.password,
                confirmPassword:formValues.confirmPassword
            }
            const res = await handleChangePassword(params);
            Toast.clear();
            if ( res.data.code === 200 ){
                console.log('onFinish called');
                Toast.success({
                    message:"密码修改成功",
                    duration:3000,
                })
                setTimeout(()=>{
                    navigate('/success');
                },3000)
            }else{
                throw new Error(res.data.message);
            }
        }catch(error:any){
            console.error('API请求错误:', error);
            // 显示错误提示，2秒后自动消失
            Toast.fail({
                message: error.message || '网络错误，请重试',
                duration: 2000
            });
        } finally{
            setIsLoading(false);
        }
    }

    const onValuesChange = () => {
        const values = form.getFieldsValue();
        setFormValues(values);
        console.log(values,formValues,'1111');
        
    }

    async function getUSer(){
        try{
            const params={
                email:email,
            }
            let res = await getUsers(params);
            if(res.data.code === 200){
                console.log(res.data.data,'res');
                setId(res.data.data._id)
            }
        }catch(error){
            console.log(error,'err');
        }
    }
    useEffect( () => {
        getUSer();
    }, []);
    return (
        <>
            <div className="new-password-container">
                <NavBar
                    title="创建新密码"
                    onClickLeft={() => { navigate('/email') }}
                />
                <div className="new-password-main">
                    <Form
                        form={form}
                        onFinish={onFinish}
                        onValuesChange={onValuesChange}
                        footer={
                            <div style={{ margin: '16px 16px 0' }}>
                                <Button
                                    round
                                    loading={isLoading}
                                    nativeType='submit'
                                    type='primary'
                                    block
                                    disabled={!form.getFieldValue('password') || !form.getFieldValue('confirmPassword')}
                                >
                                    继续
                                </Button>
                            </div>
                        }
                    >
                        <p className="parentBox-span">密码至少包含8个字符，包括大小写字母和数字</p>

                        {/* 密码输入框 */}
                        <span className="parentBox-span">设置新密码</span>
                        <Form.Item
                            name='password'
                            rules={[
                                { required: true, message: '请输入密码' },
                                {
                                    pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[A-Za-z\d@$!%*?&]{8,20}$/,
                                    message: '密码至少8个字符，包含大小写字母和数字'
                                }
                            ]}
                        >
                            <Input
                                placeholder='输入您的密码'
                                className="parentBox-input"
                                type={showPassword.password ? 'text' : 'password'}

                            />
                        </Form.Item>

                        {/* 确认密码输入框 */}
                        <span className="parentBox-span">确认新密码</span>
                        <Form.Item
                            name='confirmPassword'
                            rules={[
                                { required: true, message: '请确认密码' },
                                ({ getFieldValue }) => ({
                                    validator(_, value) {
                                        if (!value || getFieldValue('password') === value) {
                                            return Promise.resolve();
                                        }
                                        return Promise.reject(new Error('请确认两次输入的密码是否一致'));
                                    },
                                }),
                            ]}
                        >
                            <Input
                                placeholder='再次输入您的密码'
                                className="parentBox-input"
                                type={showPassword.confirmPassword ? 'text' : 'password'}

                            />
                        </Form.Item>
                    </Form>
                </div>
            </div>
        </>
    );
};

export default NewPassword;